package BanyuanClub.Study.Day0301;

import java.util.Arrays;

/**
 * 底层实现的是数组
 */
public class MyArrayList {
    private Object[] arr = new Object[5];
    private int size = 0;

    public int size(){
        return size;
    }

    //往尾部追加一个Object对象
    public void add(Object obj){
        //扩容
        if (size == arr.length){
            arr = Arrays.copyOf(arr,arr.length+5);
        }
        arr[size++] = obj;
    }

    //往头部添加元素
    public void addFirst(Object obj){

        if (size == arr.length){
            arr = Arrays.copyOf(arr,arr.length+5);
        }
//        for (int i = size; i > 0; i--) {
//            arr[i] = arr[i-1];
//        }
        System.arraycopy(arr,0,arr,1,size);
        arr[0] = obj;
        size++;
    }

    //头部移除元素
    public void removeFirst(){
        System.arraycopy(arr,1,arr,0,size-1);
        size--;
    }

    //指定索引处添加元素
    public void add(int index,Object obj){
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException();
        }
        if (size == arr.length){
            arr = Arrays.copyOf(arr,arr.length+5);
        }
        System.arraycopy(arr,index,arr,index+1,size-index);
        arr[index] = obj;
        size++;
    }

    //得到数组中的元素
    public Object get(int index){
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException();
        }
        return arr[index];
    }

    public static void main(String[] args) {
        MyArrayList myArrayList = new MyArrayList();
        myArrayList.add("aaa");
        myArrayList.add("bbb");
        myArrayList.add("ccc");
//        myArrayList.add("www");
//        myArrayList.add(2,"www");
        myArrayList.addFirst("www");
        for (int i = 0; i < myArrayList.size; i++) {
            System.out.println(myArrayList.get(i));
        }
    }

}
